package com.probiz.estore.content.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import com.probiz.estore.common.model.content.Content;
import com.probiz.estore.common.model.content.ContentMedia;
import com.probiz.estore.content.dao.ContentMediaDao;
import com.probiz.estore.content.service.ContentMediaManager;
import com.probiz.estore.core.service.impl.GenericManagerImpl;


/**
 * Manager implementation for ContentMedia, responsible for business processing, and communicate between web and persistence layer.
 */
public class ContentMediaManagerImpl extends GenericManagerImpl<ContentMedia> implements ContentMediaManager {

	private ContentMediaDao contentMediaDao = null;

	/**
	 * @param contentMediaDao
	 *            the contentMediaDao to set
	 */
	public void setContentMediaDao(ContentMediaDao contentMediaDao) {
		this.contentMediaDao = contentMediaDao;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.service.impl.GenericManagerImpl#init()
	 */
	@Override
	protected void initManager() {
		dao = contentMediaDao;
	}


	@Override
	protected void preDelete(ContentMedia entity) {
		
	}

	@Override
	protected void preSave(ContentMedia entity) {
		
	}
	/*
	 * (non-Javadoc)
	 * @see com.probiz.estore.content.service.ContentMediaManager#saveMediasFromArrays(com.probiz.estore.common.model.content.Content, java.lang.String[], java.lang.String[], java.lang.String[], java.lang.String[])
	 */
	public List<String> saveMediasFromArrays(Content content,String[] mediaIds,String[] mediaUrls,String[] mediaTypes,String[] mediaDescs){
		List<String> newMediaIdList = new ArrayList<String>();
		//删除媒体
		List<String> mediaIdList=Arrays.asList(mediaIds);
		Set<ContentMedia> formerMeidaList=content.getContentMedias();//原来的medias
		for (ContentMedia media : formerMeidaList) {
			if(!mediaIdList.contains(media.getContentMediaId().toString())){
				deleteById(media.getContentMediaId());
			}
		}
		//增加或者修改媒体
		for (int i = 0; i < mediaIds.length; i++) {
			ContentMedia media;
			if(mediaIds[i].equals("")){
				//case:新增
				media = new ContentMedia();
			}else{
				//case:修改
				media = getById(Integer.valueOf(mediaIds[i]));
			}
			media.setMediaUrl(mediaUrls[i]);
			media.setMediaType(Short.valueOf(mediaTypes[i]));
			media.setMediaDescription(mediaDescs[i]);
			media.setSortOrder(i);
			media.setContent(content);
			save(media);
			newMediaIdList.add(media.getContentMediaId().toString());
		}
		return newMediaIdList;
	}
}
